import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ToAssetControllerContext, IToAssetControllerActionEnum } from '../mconfig';
import { materialTableService } from '../services/UpdateTableService';
import { materialTableConfig } from '../mconfig';
import { Button, Col, Row, Spin, Steps, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getSelectDataMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ILoadMapTypeAll, formatDecimal } from '@/common';
import { formatDecimalFour } from '../../Acommon';
import { ToAssetControllerAPI } from '../common/type';
import { FileDoneOutlined, FileSearchOutlined } from '@ant-design/icons';
import { UpdateMaterialCollectData } from '../mview/UpdateMaterialCollectData';
import { ReceiveInfoServices } from '../services/ReceiveService';
import { UpdatePlanListCard } from '../mview/UpdatePlanListCard';

export const OpenMaterialModal: React.FC<ToAssetControllerAPI.IOpenMaterialModal> = ({ onClose, isShowModal, contractForm }) => {
  /* *弹框的ref */
  const updateModalRef: Ref<IOneModalRef> = useRef(null);
  const { prefixCls, styleFixCls, contractList } = useContext(ToAssetControllerContext);
  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  /** 资产类型 */
  const assetTypeList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);
  /** 获取上下文 */
  const { materielList, curRes, toAssetControllerDispatch } = useContext(ToAssetControllerContext);
  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(curRes);
  /** 表格数据 */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);
  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);
  /** 选中树的key */
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);
  /** 步骤条位置 */
  const [currentStep, setCurrentStep] = useState(0);
  /** 步骤条渲染步骤 */
  const stepsItems = [
    { title: '选择材料', key: 'select-pack', icon: <FileSearchOutlined /> },
    { title: '确认信息', key: 'comfirm-msg', icon: <FileDoneOutlined /> },
  ];
  /** 计划列表 - services */
  const { getReceiveListRun, getReceiveListDataSource, getReceiveListLoading, getReceiveListTableProps } = ReceiveInfoServices(
    curRes,
  )?.getReceiveInfoServices();

  /** 左侧类型树搜索 */
  const [typeTreeSearchObj, setTypeTreeSearchObj] = useState<Record<string, any>>({
    searchValue: '',
    expandedKeys: [],
  });

  useEffect(() => {
    let dataRow: Record<string, any>[] = [];
    if (data?.rows?.length >= 0) {
      dataRow = JSON.parse(JSON.stringify(data?.rows));
      // 添加总价和数量字段
      for (let i = 0; i < dataRow.length; i++) {
        dataRow[i].validNum = dataRow[i].residueNum;
        dataRow[i].totalPrice = 0;
        dataRow[i].stuffId = dataRow[i].id;
      }
      if (materielList.length !== 0) {
        for (let i = 0; i < materielList.length; i++) {
          let idx = dataRow.findIndex((item: Record<string, any>) => {
            return item.id === materielList[i].id;
          });
          if (idx !== -1) {
            dataRow[i].validNum = Number(materielList[i].validNum);
          }
        }
      }
      setDataSource(dataRow);
    }
  }, [data]);

  /** 左侧搜索 */
  const searchLeftList = (obj: any) => {
    getReceiveListRun(obj);
  };

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    setCheckMaterialList(selectInfo);
  };

  /** 修改材料数量 */
  const changeNum = (id: string | number, value: string | number) => {
    /** 修改表格材料数量 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.id === id;
    });
    if (idx !== -1) {
      let arr = JSON.parse(JSON.stringify(dataSource));
      arr[idx].validNum = value;
      setDataSource(arr);
    }
    /** 修改选中材料数量 */
    let checkIdx = checkMaterialList.findIndex((item: Record<string, any>) => {
      return item.id === id;
    });
    if (checkIdx !== -1) {
      let arr = JSON.parse(JSON.stringify(checkMaterialList));
      arr[checkIdx].validNum = value;
      setCheckMaterialList(arr);
    }
  };

  /** 选中的材料改变左侧领用单的角标 */
  const PlanIdsMemo = useMemo(() => {
    if (checkMaterialList?.length) {
      let ReceiveIDS: any[] = checkMaterialList?.map((item) => item?.applyId);
      return Array.from(new Set(ReceiveIDS));
    } else {
      return [];
    }
  }, [checkMaterialList]);

  /** 初始化 */
  useEffect(() => {
    /** 获取左侧领用列表 */
    getReceiveListRun({});
    /** 获取右侧列表 */
    getManageData({});
    /** 回显选中的项 */
    setCheckMaterialList(materielList);
  }, [isShowModal]);

  /** 点击取消 */
  const cancel = () => {
    setCheckMaterialList([]);
    onCloseModalCommon(updateModalRef);
  };

  /** 点击确定 */
  const submit = () => {
    /** 存储到仓库 */
    toAssetControllerDispatch({
      type: IToAssetControllerActionEnum.SELECT_MATERIEL,
      payload: checkMaterialList,
    });
    onCloseModalCommon(updateModalRef);
  };

  /** 表格操作按钮 */
  const modalFooterRender = () => {
    return (
      <>
        {currentStep == 0 ? (
          <Button
            onClick={() => {
              cancel();
            }}
          >
            取消
          </Button>
        ) : (
          <Button onClick={() => setCurrentStep(0)}>上一步</Button>
        )}
        {currentStep == 0 ? (
          <Button
            onClick={() => {
              if (checkMaterialList && checkMaterialList?.length > 0) {
                /** 校验选中的材料数量是否为0 */
                let idx = checkMaterialList.findIndex((item: Record<string, any>) => {
                  return item.validNum === '' || item.validNum === 0;
                });
                if (idx !== -1) {
                  message.warning('请输入材料数量');
                  return;
                }
                /** 计算总价 */
                for (let i = 0; i < checkMaterialList.length; i++) {
                  checkMaterialList[i].totalPrice = Number(formatDecimalFour(Number(checkMaterialList[i].validNum) * Number(checkMaterialList[i].assetValue)));
                }
                let arr = JSON.parse(JSON.stringify(checkMaterialList));
                setCheckMaterialList(arr);
                /** 存储到仓库 */
                // toAssetControllerDispatch({
                //   type: IToAssetControllerActionEnum.SELECT_MATERIEL,
                //   payload: arr,
                // });
                setCurrentStep(1);
              } else {
                message.error('请至少选择一个材料');
              }
            }}
            disabled={checkMaterialList?.length === 0}
          >
            下一步
          </Button>
        ) : (
          <Button type={'primary'} onClick={submit}>
            确认
          </Button>
        )}
      </>
    );
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'材料列表'}
        width={1400}
        onCancel={onClose as any}
        footer={modalFooterRender()}
        bodyStyle={{
          height: '650px',
          // height: '250px',
          padding: '10px 20px',
          overflow: 'hidden',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <div className={prefixCls + '-selectPackAgeTopTitle'}>
          <Steps
            size={'default'}
            current={currentStep}
            items={stepsItems}
            // onChange={(current) => setCurrentStep(current)}
          />
        </div>
        {currentStep == 0 ? (
          <Row className={`${styleFixCls}materialModal`}>
            <Col span={6}>
              <Spin spinning={getReceiveListLoading}>
                <UpdatePlanListCard
                  onSelect={(val) => {
                    getManageData({ applyId: val });
                  }}
                  onChange={{ selectKeys, setSelectKeys, typeTreeSearchObj, setTypeTreeSearchObj, searchLeftList }}
                  dataSource={getReceiveListDataSource}
                  PlanIdsMemo={PlanIdsMemo}
                  loading={getReceiveListLoading}
                  getPlanSev={() => {
                    let { current, pageSize, total }: Record<string, any> = getReceiveListTableProps?.pagination;
                    /** 避免多次请求 */
                    // if (getPlanListDataSource?.length < total) {
                    //   getPlanListRun({ ...PlanManageTab(curRes), current, pageSize: pageSize + 10 });
                    // }
                  }}
                />
              </Spin>
            </Col>
            <Col span={18}>
              <UpdateTableCommon
                styleFixCls={styleFixCls}
                searchProps={{
                  searchList,
                  onReset,
                  onSearch,
                }}
                selectTablePorps={{
                  onSelectTable,
                  selectRowObjList: checkMaterialList,
                  selectType: 'checkbox',
                  setCheckRows: setCheckMaterialList,
                  getCheckboxProps: (record: Record<string, any>) => ({
                    disabled: record.residueNum == 0,
                  }),
                }}
                tableProps={{
                  columns: materialTableConfig(assetTypeList, changeNum),
                  loading,
                  dataSource: dataSource,
                  pagination,
                  onPageChange,
                  rowKey: 'stuffId',
                  tableTotalShow: (total: any, range: any) => {
                    return (
                      <div
                        style={{
                          display: 'flex',
                          width: '100%',
                          justifyContent: 'space-between',
                        }}
                      >
                        <div>
                          已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条材料
                        </div>
                        <div>{showTotalInfo(total, range)}</div>
                      </div>
                    );
                  },
                }}
              />
            </Col>
          </Row>
        ) : (
          <UpdateMaterialCollectData dataSource={checkMaterialList} />
        )}
      </OneModal>
    </>
  );
};
